<?php
declare(strict_types=1);

namespace lib\data\traits;

trait MidStoreTrait {
    static array $mid_cache = [];
    static array $store_cache = [];
    static array $pk = [];

    protected function traitInit(){
        static::$pk[$this->id] = $this;
        static::$mid_cache[$this->mid][$this->id] = $this;
        static::$store_cache[$this->store_id][$this->goods_id] = $this;
    }

    public static function getAll(int $mid){
        return array_values(static::$mid_cache[$mid]??[]);
    }
    
    public static function getByStoreId(int $store_id) :array{
        return array_values(static::$store_cache[$store_id]??[]);
    }

    public static function getGoodsFromStoreId(int $store_id, int $goods_id, bool &$is_new, ?\sys\Db $db = null) :?static {
        $static = static::$store_cache[$store_id][$goods_id] ?? null;
        if(null !== $db){
            if($is_new = (null === $static)){
                if(null === ($goods = \lib\data\Components::get($goods_id))){
                   return null;
                }
                $row = [
                    'store_id'=>$store_id,
                    'goods_id'=>$goods_id,
                    'mid'=>$goods->mid,
                    'store_num'=>0,
                    'on_sale'=>$goods->on_sale
                ];
                $row['id'] = $db->table('tp_nb_goods_store_map')->insert($row);
                return static::createInstance($row);
            }
            return $static;
        }
        $is_new = false;
        return $static;
    }
    
    public static function waitGoodsFromStoreId(\sys\Db $db, int $store_id, int $goods_id, bool &$is_new) :?static {
        $static = static::getGoodsFromStoreId($store_id, $goods_id, $is_new, $db);
        if(null === $static){
            return null;
        }
        return $static->waitLock();
    }

    public static function get(int $id) :?static{
        return static::$pk[$id]??null;
    }

    public function remove(){
        unset(static::$pk[$this->id]);
        unset(static::$mid_cache[$this->mid][$this->id]);
        unset(static::$store_cache[$this->store_id][$this->goods_id]);
    }

    
}